package com.ljb.utilslibrary.commUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * 文件相关工具类
 * Created by ljb on 2017/6/29.
 */

public class FileUtils {
    private FileUtils() {
    }

    /**
     * 读取文件中的内容
     *
     * @param filePath    文件路径
     * @param charsetName 文件编码
     * @return 读取失败返回null
     */
    public static StringBuilder readFile(String filePath, String charsetName) {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        StringBuilder fileContent = new StringBuilder("");
        BufferedReader reader = null;
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charsetName);
            reader = new BufferedReader(isr);
            String line;
            while ((line = reader.readLine()) != null) {
                if (!fileContent.toString().equals("")) {
                    fileContent.append("\r\n");
                }
                fileContent.append(line);
            }
            reader.close();
            return fileContent;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}



























